package com.yc.c110s2plyqnzf.controller;

import com.yc.c110s2plyqnzf.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class IndexDo {

    @Value("${uploadDir}")
    private String uploadDir;

    @PostMapping("upload")
    Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        File dir = new File(uploadDir.substring("file:/".length()));
        // 生成随机文件名
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        final String originalFilename = file.getOriginalFilename();
        // 截取文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 拼接新的文件名
        filename += suffix;
        File fileObj = new File(dir, filename);
        // 保存
        file.transferTo(fileObj);
        // 返回文件的web路径
        String webpath = "/upload/" + filename;
        return new Result(1,  "文件上传成功!", webpath);
    }

}
